package ShoppingCart;

import Change.ChangeInfo;
import Change.ChangePassword;
import EncapsulatingObjects.Trip;
import EncapsulatingObjects.User;
import LoginSystem.LoginPage;
import Manage.ViewAllTrip;
import TextDocument.UserAgreement;
import Util.ShoppingCartUtil;
import Util.TripDatabaseUtil;
import Util.UiUtil;
import Util.UserDatabaseUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Shop {
    JFrame jf;
    JTable table;
    JScrollPane sp;
    JButton OK;
    JLabel CANCEL;
    JLabel sPosition;
    JLabel ePosition;
    JComboBox jsPosition;
    JComboBox jePosition;

    JMenuBar jb;
    JMenu home;
    JMenu mUser;
    JMenu shopCar;
    JMenu help;

    JMenuItem myHome;
    JMenuItem cInfo;
    JMenuItem cPass;
    JMenuItem mlogout;

    JPopupMenu rightClick;

    boolean statue;
    TripDatabaseUtil td = new TripDatabaseUtil();
    UserDatabaseUtil ud = new UserDatabaseUtil();
    ShoppingCartUtil su = new ShoppingCartUtil();
    static ArrayList<String> columns;
    static String[] columnCount;
    List<Trip> trips;
    User currentUser = new User();

    void init() {
        jf = new JFrame("Manage");
        jf.setSize(1175, 740);
        jf.setLayout(null);
        isAdmin();

        jf.setResizable(false);
        sp = new JScrollPane();
        sp.setBounds(30, 100, 1100, 580);
        jf.add(sp);

        jb = new JMenuBar();
        home = new JMenu("View All Trip");

        mUser = new JMenu("User");
        shopCar = new JMenu("Shopping cart");
        shopCar.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                ViewAllTrip.buttonName = "Submit";
                new ViewAllTrip();
            }
        });
        help = new JMenu("Help Me");
        help.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                UserAgreement.isHelp = true;
                new UserAgreement();
            }
        });

        myHome = new JMenuItem("My Homepage");
        myHome.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jf.dispose();
            }
        });

        cInfo = new JMenuItem("Change Information");
        cInfo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new ChangeInfo();
            }
        });
        cPass = new JMenuItem("Change Password");
        cPass.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new ChangePassword();
            }
        });
        mlogout = new JMenuItem("Log Out");
        mlogout.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                logout();
            }
        });

        jb.setBackground(Color.LIGHT_GRAY);
        jb.setBounds(0, 0, 1175, 32);

        jb.add(home);
        jb.add(mUser);
        jb.add(shopCar);
        jb.add(help);

        mUser.add(myHome);
        mUser.add(cInfo);
        mUser.add(cPass);
        mUser.add(mlogout);

        jf.add(jb);

        rightClick = new JPopupMenu();
        JMenuItem fresh = new JMenuItem();
        fresh.setText("  FRESH  ");
        fresh.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                viewAll(false);
            }
        });

        JMenuItem raddToCart = new JMenuItem();
        raddToCart.setText("Add to My Cart");
        raddToCart.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                addToCart();
            }
        });

        rightClick.add(fresh);
        rightClick.add(raddToCart);

        table = new JTable();
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                tableMouseClicked(e);
            }
        });
        table.setDefaultRenderer(Object.class, new ShoppingCart.TableCellTextAreaRenderer());
        sp.setViewportView(table);

        sPosition = new JLabel("Start Position");
        sPosition.setBounds(30, 50, 100, 30);
        jf.add(sPosition);
        jsPosition = new JComboBox();
        jsPosition.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                selectTrip();
            }
        });
        jsPosition.setBounds(120, 50, 150, 30);
        jf.add(jsPosition);
        ePosition = new JLabel("End Position");
        ePosition.setBounds(350, 50, 100, 30);

        jf.add(ePosition);
        jePosition = new JComboBox();
        jePosition.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                selectTrip();
            }
        });
        jePosition.setBounds(430, 50, 150, 30);
        jf.add(jePosition);

        OK = new JButton("Add to Cart");
        OK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addToCart();
            }
        });
        OK.setBounds(890, 50, 150, 30);
        OK.setOpaque(true);
        OK.setBackground(Color.CYAN);
        OK.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        jf.add(OK);

        CANCEL = new JLabel("Reset", JLabel.CENTER);
        CANCEL.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                initPosition();
                viewAll(false);
            }
        });
        CANCEL.setBounds(1040, 50, 100, 30);
        CANCEL.setForeground(Color.gray);
        CANCEL.setFont(new Font("Harlow Solid Italic", Font.BOLD, 20));
        CANCEL.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        jf.add(CANCEL);
    }

    private void selectTrip() {
        trips = td.quaryAll(su.viewMyCart(currentUser, 1));
        if ("--".equals(jsPosition.getSelectedItem()) && "--".equals(jePosition.getSelectedItem())){

        }
        if ("--".equals(jsPosition.getSelectedItem()) && !"--".equals(jePosition.getSelectedItem())){
            trips = selecteTrip();
        }
        if (!"--".equals(jsPosition.getSelectedItem()) && "--".equals(jePosition.getSelectedItem())){
            trips = selectsTrip();
        }
        if(!"--".equals(jsPosition.getSelectedItem()) && !"--".equals(jePosition.getSelectedItem())){
            trips = selectsTrip();
            trips = selecteTrip();
        }
        viewAll(true);
    }

    private List<Trip> selectsTrip() {
        String start = String.valueOf(jsPosition.getSelectedItem()).trim();
        for (int i = 0; i < trips.size(); i++) {
            if (!start.equals(trips.get(i).getsPosition())) {
                trips.remove(i);
                i--;
            }
        }
        return trips;
    }

    private List<Trip> selecteTrip() {
        String end = String.valueOf(jePosition.getSelectedItem()).trim();
        for (int i = 0; i < trips.size(); i++) {
            if (!end.equals(trips.get(i).getePosition())) {
                trips.remove(i);
                i--;
            }
        }
        return trips;
    }

    private void addToCart() {
        ShoppingCartUtil su = new ShoppingCartUtil();
        su.updateTripToCart(currentUser, trips.get(table.getSelectedRow()), 2);
        JOptionPane.showMessageDialog(jf, "Successfully added to cart!");
        viewAll(false);
    }

    private void logout() {
        if (JOptionPane.showConfirmDialog(jf, "Are you sure you want to log out") == JOptionPane.YES_OPTION) {
            User user = new User();
            UserDatabaseUtil du = new UserDatabaseUtil();
            du.initUser(user);
            du.updateLoginStatue(user, false);
            jf.dispose();
            new LoginPage();
        }
    }

    private void viewAll(boolean select) {
        if (!select)
            trips = td.quaryAll(su.viewMyCart(currentUser, 1));
        Object[][] data = new Object[trips.size()][];
        for (int i = 0; i < trips.size(); i++) {
            Trip t = trips.get(i);
            Object[] info = new Object[]{t.getId(), t.getName(), t.getsPosition(), t.getePosition(),
                    t.getsDate(), t.geteDate(), t.getHotelNamex(), t.getDoWhat(), t.getMoney(),};
            data[i] = info;
        }
        table.setModel(new DefaultTableModel(data, columnCount));
    }

    public Shop() {
        init();
        ud.initUser(currentUser);
        initPosition();
        columns = td.getColumn();
        columnCount = new String[columns.size()];
        for (int i = 0; i < columns.size(); i++) {
            columnCount[i] = columns.get(i);
        }

        viewAll(false);
        UiUtil.setFrameCenter(jf);
        jf.setVisible(true);
    }

    private void initPosition() {
        jsPosition.removeAllItems();
        jePosition.removeAllItems();
        trips = td.quaryAll(su.viewMyCart(currentUser, 1));
        ArrayList sp = new ArrayList();
        ArrayList ep = new ArrayList();
        for (int i = 0; i < trips.size(); i++) {
            if (!sp.contains(trips.get(i).getsPosition()))
                sp.add(trips.get(i).getsPosition());
            if (!ep.contains(trips.get(i).getePosition()))
                ep.add(trips.get(i).getePosition());
        }
        jsPosition.addItem("--");
        for (int i = 0; i < sp.size(); i++) {
            jsPosition.addItem(sp.get(i));
        }
        jePosition.addItem("--");
        for (int i = 0; i < ep.size(); i++) {
            jePosition.addItem(ep.get(i));
        }
    }

    public void isAdmin() {
        UserDatabaseUtil ud = new UserDatabaseUtil();
        try {
            Connection conn = ud.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from userdata");
            while (rs.next()) {
                if (rs.getBoolean("isLogin") == true) {
                    statue = rs.getBoolean("isAdmin");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void tableMouseClicked(MouseEvent e) {
        mouseRightButtonClick(e);
    }

    private void mouseRightButtonClick(java.awt.event.MouseEvent evt) {
        //判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键
        if (evt.getButton() == MouseEvent.BUTTON3) {
            //通过点击位置找到点击为表格中的行
            int focusedRowIndex = table.rowAtPoint(evt.getPoint());
            if (focusedRowIndex == -1) {
                return;
            }
            //将表格所选项设为当前右键点击的行
            table.setRowSelectionInterval(focusedRowIndex, focusedRowIndex);
            //弹出菜单
            rightClick.show(table, evt.getX(), evt.getY());
        }
    }
}

class TableCellTextAreaRenderer extends JTextArea implements TableCellRenderer {
    @Override
    public void setSelectionColor(Color c) {
        super.setSelectionColor(c);
    }

    public TableCellTextAreaRenderer() {
        setLineWrap(true);
        setWrapStyleWord(true);
    }

    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected, boolean hasFocus, int row, int column) {
        // 计算当下行的最佳高度
        int maxPreferredHeight = 0;
        for (int i = 0; i < table.getColumnCount(); i++) {
            setText("" + table.getValueAt(row, i));
            setSize(table.getColumnModel().getColumn(column).getWidth(), 0);
            maxPreferredHeight = Math.max(maxPreferredHeight, getPreferredSize().height);
        }

        if (table.getRowHeight(row) != maxPreferredHeight)  // 少了这行则处理器瞎忙
            table.setRowHeight(row, maxPreferredHeight);

        setText(value == null ? "" : value.toString());
        return this;
    }
}